// pages/publish/publish.js
Page({
  data: {
    publishType: 'lost', // lost: 失物, found: 招领
    categories: ['电子产品', '证件卡片', '衣物配饰', '学习用品', '生活用品', '其他'],
    categoryIndex: null,
    date: '',
    time: '',
    images: [],
    contact: ''
  },
  
  setPublishType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      publishType: type
    });
  },
  
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    });
  },
  
  bindTimeChange: function(e) {
    this.setData({
      time: e.detail.value
    });
  },
  
  chooseImage: function() {
    const that = this;
    if (this.data.images.length >= 3) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count: 3 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          images: that.data.images.concat(res.tempFilePaths)
        });
      }
    });
  },
  
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images;
    images.splice(index, 1);
    this.setData({
      images: images
    });
  },
  
  formSubmit: function(e) {
    const formData = e.detail.value;
    
    // 表单验证
    if (!formData.name) {
      wx.showToast({
        title: '请输入物品名称',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.categoryIndex === null) {
      wx.showToast({
        title: '请选择物品分类',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.date || !this.data.time) {
      wx.showToast({
        title: '请选择时间',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.location) {
      wx.showToast({
        title: '请输入地点',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.description) {
      wx.showToast({
        title: '请输入详细描述',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.contact) {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      });
      return;
    }
    
    // 提交表单
    wx.showLoading({
      title: '发布中...',
    });
    
    // 模拟网络请求
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '发布成功',
        icon: 'success'
      });
      
      // 重置表单
      this.setData({
        categoryIndex: null,
        date: '',
        time: '',
        images: []
      });
      
      // 返回首页
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index'
        });
      }, 1500);
    }, 2000);
  }
});